package logmgr;

import Common.ByteArray;
import Common.GoggleDB;
import storage.data.Page;
import storage.data.PageID;



public class BytesRecord extends LogMgr {
	public byte[] old, cur ;
	
	public void redo (){ 
//		System.out.printf ( "REDO transaction:%d page:%d offset:%d from the value:%d to value:%d\n",
//		txnum, pageid,  pos, (Integer)old, (Integer)cur ) ;
		System.out.println ( "Byte Array has been redo") ;
		try {
			PageID pid = new PageID ( pageid ) ;
			Page aPage = new Page () ; 
			GoggleDB.bufferMgr.pinPage(pid, aPage, false) ;
			System.arraycopy(cur, 0, aPage.getData(), pos, cur.length) ; 
			GoggleDB.bufferMgr.unpinPage(pid, true ) ;
			GoggleDB.bufferMgr.flush( pid ) ;
		}catch ( Exception e ) {
		}
		
	} 
	
	public void undo () {
		System.out.println ( "Byte Array has been undo") ;
//		System.out.printf ( "UNDO transaction:%d page:%d offset:%d from the value:%d to value:%d\n",
//				txnum, pageid, pos, (Integer)old, (Integer)cur ) ;
		try {
			PageID pid = new PageID ( pageid ) ;
			Page aPage = new Page () ; 
			GoggleDB.bufferMgr.pinPage(pid, aPage, false) ;
			System.arraycopy(old, 0, aPage.getData(), pos, cur.length) ; 
			GoggleDB.bufferMgr.unpinPage(pid, true ) ;
			GoggleDB.bufferMgr.flush( pid ) ;
		}catch ( Exception e ) {
		}
	}
	
	public void read () throws Exception {
//		long point = file.getFilePointer() ;
//		file.seek( point + 12 );
//		file.read( buff ) ;
//		int len = readInt ( buff, 0 ) ;
		
		byte[] buff = new byte [ 16 ] ; 
		file.read( buff ) ;
		txnum = ByteArray.readInt ( buff,  0 ) ;
		pageid = ByteArray.readInt ( buff, 4 ) ;
		pos = ByteArray.readInt ( buff, 8 ) ;
		int len  = ByteArray.readInt ( buff, 12 ) ;
		
		old = new byte [ len ] ; 
		file.read( old ) ;
		cur = new byte [ len ] ; 
		file.read( cur ) ;
	}
	
	@Override
	public void write ( int txnum, int pageid, int pos, Object old, Object cur ) throws Exception {
		byte[] bs1 = (byte[])old ;
		byte[] bs2 = (byte[])cur ; 
		byte [] buff = new byte [ 20 + bs1.length + bs2.length ] ;
		ByteArray.writeInt ( buff, 0, BYTES ) ;
		ByteArray.writeInt ( buff, 4, txnum ) ;
		ByteArray.writeInt ( buff, 8, pageid ) ;
		ByteArray.writeInt ( buff, 12, pos ) ;
		ByteArray.writeInt ( buff, 16, bs1.length ) ;
		System.arraycopy( bs1, 0, buff, 20, bs1.length) ; 
		System.arraycopy( bs2, 0, buff, 20 + bs1.length , bs2.length) ; 
		file.seek( file.length() ) ;
		file.write ( buff ) ; 
	}
}
